<template>
  <el-dialog v-model="visible" title="分配医院" width="800px" append-to-body @open="open" @close="cancel">
    <div class="assign-hospital-container">
      <!-- 项目信息展示 -->
      <div class="item-info">
        <h3>项目信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">{{ currentItem.name }}</el-descriptions-item>
          <el-descriptions-item label="项目描述">{{ currentItem.description }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 分配医院表单 -->
      <div class="assign-form">
        <h3>分配医院</h3>
        <el-form :model="assignForm" :rules="assignRules" ref="assignFormRef" label-width="100px">
          <el-form-item label="选择医院" prop="hospitalId">
            <el-select 
              v-model="assignForm.hospitalId" 
              placeholder="请选择医院" 
              style="width: 100%"
              filterable
              @change="handleHospitalChange"
            >
              <el-option
                v-for="hospital in availableHospitals"
                :key="hospital.id"
                :label="hospital.name"
                :value="hospital.id"
              >
                <span style="float: left">{{ hospital.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ hospital.level }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="设置价格" prop="price">
            <el-input-number
              v-model="assignForm.price"
              :min="0"
              :precision="2"
              placeholder="请输入价格"
              style="width: 100%"
            />
            <div class="price-tip">价格单位为元，支持小数点后两位</div>
          </el-form-item>

        </el-form>
      </div>

      <!-- 已分配的医院列表 -->
      <div class="assigned-hospitals" v-if="assignedHospitals.length > 0">
        <h3>已分配医院</h3>
        <el-table :data="assignedHospitals" stripe max-height="250">
          <el-table-column prop="hospitalName" label="医院名称" align="center" />
          <el-table-column prop="price" label="价格(元)" align="center" width="120">
            <template #default="scope">
              <span class="price-text">¥{{ formatPrice(scope.row.price) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button type="danger" size="small" @click="handleRemoveAssignment(scope.row)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleSubmit">
          确认分配
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { listHospital } from '@/api/hospital/hospital';
import { assignItemToHospital, getItemHospitalAssignments, removeItemHospitalAssignment } from '@/api/item/item';
import { centsToYuan } from '@/utils/money'

const { proxy } = getCurrentInstance();

// 定义 props
const props = defineProps({
  assignHospitalVisible: {
    type: Boolean,
    default: false
  },
  currentItem: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['handleClose', 'handleSuccess']);
const visible = ref(false);
watch(
  () => props.assignHospitalVisible,
  (val) => {
    visible.value = val;
  }
);

// 响应式数据
const hospitalList = ref([]);
const assignedHospitals = ref([]);
const assignFormRef = ref(null);

// 分配表单数据
const assignForm = reactive({
  hospitalId: '',
  price: null
});

// 表单验证规则
const assignRules = {
  hospitalId: [
    { required: true, message: '请选择医院', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ]
};

// 计算属性：过滤已分配的医院
const availableHospitals = computed(() => {
  const assignedIds = assignedHospitals.value.map(item => item.hospitalId);
  return hospitalList.value.filter(hospital => !assignedIds.includes(hospital.id));
});

// 价格格式化
const formatPrice = (price) => centsToYuan(price);

// 获取医院列表
const getHospitalList = () => {
  listHospital({ pageNum: 1, pageSize: 1000 }).then((res) => {
    hospitalList.value = res.rows || [];
  });
};  

// 获取已分配的医院
const getAssignedHospitals =  () => {
  getItemHospitalAssignments(props.currentItem.id).then((res) => {
    assignedHospitals.value = res.data || [];
  });
};

// 提交分配
const handleSubmit = () => {
  if (!assignFormRef.value) return;
  
  assignFormRef.value.validate().then(() => {
    assignItemToHospital({
      itemId: props.currentItem.id,
      hospitalId: assignForm.hospitalId,
      price: assignForm.price * 100,
    }).then(() => {
      visible.value = false;
      emit('handleSuccess');
    });
  });
};

// 移除分配
const handleRemoveAssignment = (row) => {
  proxy.$modal.confirm(`确定要移除医院"${row.hospitalName}"的分配吗？`).then(() => {
    removeItemHospitalAssignment(props.currentItem.id, row.hospitalId).then(() => {
      proxy.$modal.msgSuccess('移除分配成功');
      getAssignedHospitals();
    });
  })
};

// 重置表单
const handleReset = () => {
  assignForm.hospitalId = '';
  assignForm.price = null;
  if (assignFormRef.value) {
    assignFormRef.value.clearValidate();
  }
};

const open = () => {
  getHospitalList();
  getAssignedHospitals();
};

const cancel = () => {
  visible.value = false;
  handleReset();
  emit('handleClose');
};
</script>

<style scoped lang="scss">
.assign-hospital-container {
  padding: 10px 20px;

  .item-info {
    margin-bottom: 20px;
    
    h3 {
      margin-bottom: 15px;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .assign-form {
    margin-bottom: 20px;
    
    h3 {
      margin-bottom: 15px;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }

    .price-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 5px;
    }
  }

  .assigned-hospitals {
    margin-bottom: 20px;
    
    h3 {
      margin-bottom: 15px;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }

    .price-text {
      color: #f56c6c;
      font-weight: 600;
    }
  }

  .action-buttons {
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
  }
}

:deep(.el-descriptions) {
  .el-descriptions__label {
    font-weight: 600;
  }
}

:deep(.el-table) {
  .el-table__header {
    background-color: #f5f7fa;
  }
  
  .el-table__header th {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
  }
  
  .el-table__row:hover {
    background-color: #f5f7fa;
  }
}
</style>
